package com.feihong.yw189.activity.tiaoxingma;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.ImageButton;

import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;

import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.ArrayList;

import me.dm7.barcodescanner.zbar.BarcodeFormat;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Sabirjan on 2017/6/29.
 * TXGWApp.
 * 飞宏电子
 */
@RuntimePermissions
public class TiaoXingMaActivity extends BaseActivity implements ZBarScannerView.ResultHandler {
    public static final String INTENT_ICCID = "intent_iccid";
    public static final int REQ_CODE = 887;
    /**
     * 二维码/条形码扫描控件
     */
    public ZBarScannerView mScannerView;
    private boolean isNeeds = true;
    private ImageButton btn_back;
    private static final String TAG = "扫码";
    private MyUsualyDialog progressDialog;
    private String currentICCID = "";
    private boolean isSuccess = false;
    private Callback.Cancelable cancelable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //保持长亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_scanner);
        progressDialog = new MyUsualyDialog(TiaoXingMaActivity.this, R.layout.wait_item);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        mScannerView = (ZBarScannerView) findViewById(R.id.mZXingScannerView);
        btn_back = (ImageButton) findViewById(R.id.scanner_iv_back);
        btn_back.setOnClickListener(v -> finish());
        ArrayList<BarcodeFormat> list = new ArrayList<>();
        list.add(BarcodeFormat.CODABAR);
        list.add(BarcodeFormat.CODE39);
        list.add(BarcodeFormat.CODE128);
        mScannerView.setFormats(list);
        TiaoXingMaActivityPermissionsDispatcher.onNeedsPermissionWithCheck(this);
    }

    @Override
    public void setTheme() {

    }

    public void over() {
        currentICCID = "";
        isSuccess = false;
        vibrate();
        new Handler().postDelayed(() -> mScannerView.resumeCameraPreview(TiaoXingMaActivity.this), 1000);
    }

    /**
     * 震动
     */
    public void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mScannerView != null && isNeeds) {
            mScannerView.resumeCameraPreview(TiaoXingMaActivity.this);
        }
    }

    private void openCamera() {
        if (isNeeds) {
            new Handler().postDelayed(() -> {
                mScannerView.setResultHandler(TiaoXingMaActivity.this);
                try {
                    mScannerView.startCamera();
                    // Start camera on resume
                } catch (Exception ex) {
                    ex.printStackTrace();
                    showErrorDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            finish();
                        }
                    });
                }
            }, 200);
        } else {
            showErrorDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    finish();
                }
            });
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mScannerView.stopCamera();           // Stop camera on pause
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @NeedsPermission(Manifest.permission.CAMERA)
    void onNeedsPermission() {
        isNeeds = true;
        openCamera();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        TiaoXingMaActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void onPermissionDenied() {
        isNeeds = false;
        showErrorDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void onNeverAskAgain() {
        isNeeds = false;
        showErrorDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }
    /**
     * 扫码返回结果
     */
    @Override
    public void handleResult(final Result result) {
        if (result.getOpenState() == -1) {
            showErrorDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    finish();
                }
            });
            return;
        }
        String content = result.getContents();
        onScanQRCodeSuccess(content);
    }

    private boolean isICCIC(String input) {
        if (TextUtils.isEmpty(input) || input.trim().length() != 19) {
            return false;
        }
        for (int i = 0; i < 19; i++) {
            char c = input.charAt(i);
            if (!(c <= '9' && c >= '0')) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断读出的内容是否是所需要的内容
     * 这里具体为判断是否是iccid
     * @param result
     */
    public void onScanQRCodeSuccess(String result) {
        if (cancelable != null && !cancelable.isCancelled()) {
            cancelable.cancel();
        }
        if (!isICCIC(result)) {
            over();
            return;
        }
        vibrate();
        currentICCID = result.trim();
        progressDialog.show();
        cancelable = new HttpTools().checkICCID(currentICCID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (activityIsDestory()) {
                    return;
                }
                try {
                    JSONObject object = new JSONObject(result);
                    if (object.getInt("status") == 1) {
                        isSuccess = true;
                    } else {
                        String msg = object.getString("info");
                        showInfoToast(msg);
                        isSuccess = false;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    isSuccess = false;
                    showToast("数据出错，请重试！");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (activityIsDestory()) {
                    return;
                }
                showToast("网络出错，请重试！");
                isSuccess = false;
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (activityIsDestory()) {
                    return;
                }
                try {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    if (isSuccess) {
                        //成功
                        Intent intent = new Intent();
                        intent.putExtra(INTENT_ICCID, currentICCID);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    } else {
                        over();
                    }
                } catch (Exception ex) {
                }
            }
        });
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    public void rationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", (dialog, which) -> request.proceed())
                .setNegativeButton("拒绝", (dialog, which) -> request.cancel())
                .setCancelable(false)
                .setMessage("请允许获取相机权限")
                .show();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}